package com.shxc.smarttrade.position.old;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Matrix;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TextView;

import com.akexorcist.roundcornerprogressbar.RoundCornerProgressBar;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.jcodecraeer.xrecyclerview.ProgressStyle;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.shxc.smarttrade.MyApplication;
import com.shxc.smarttrade.R;
import com.shxc.smarttrade.login.activity.LoginHomeActivity;
import com.shxc.smarttrade.main.MainActivity;
import com.shxc.smarttrade.old.activity.ChooseBrokerActivity;
import com.shxc.smarttrade.old.activity.PendingOrderDetailActivity;
import com.shxc.smarttrade.old.activity.RechargeActivity;
import com.shxc.smarttrade.old.activity.StockChartUpgradeActivity;
import com.shxc.smarttrade.old.activity.UserAgreementActivity;
import com.shxc.smarttrade.old.activity.WithdrawDepositActivity;
import com.shxc.smarttrade.old.adapter.AllPositionAdapter;
import com.shxc.smarttrade.old.adapter.BrokerAdapter;
import com.shxc.smarttrade.old.adapter.PositionHistoryAdapter;
import com.shxc.smarttrade.old.adapter.PositionPendingAdapter;
import com.shxc.smarttrade.old.bean.AccountInfo;
import com.shxc.smarttrade.old.bean.AccountInfomation;
import com.shxc.smarttrade.old.bean.Broker;
import com.shxc.smarttrade.old.bean.EventDatas;
import com.shxc.smarttrade.old.bean.ForeignOrder;
import com.shxc.smarttrade.old.bean.PendOrder;
import com.shxc.smarttrade.old.bean.PositionHistory;
import com.shxc.smarttrade.old.bean.PositionOrderList;
import com.shxc.smarttrade.old.bean.RealTimeQuoteDatas;
import com.shxc.smarttrade.old.bean.TraderOrder;
import com.shxc.smarttrade.old.bean.UserInfo;
import com.shxc.smarttrade.old.constants.EventContents;
import com.shxc.smarttrade.old.constants.URLContents;
import com.shxc.smarttrade.old.iview.IViewAccount;
import com.shxc.smarttrade.old.iview.IViewPosition;
import com.shxc.smarttrade.old.myinterface.PositionItemClickListener;
import com.shxc.smarttrade.old.myview.CommonDialog;
import com.shxc.smarttrade.old.myview.MyFootView;
import com.shxc.smarttrade.old.myview.MyProgressDialog;
import com.shxc.smarttrade.old.myview.MyRefreshHeadView;
import com.shxc.smarttrade.old.myview.RecycleViewDivider;
import com.shxc.smarttrade.old.myview.RecycleViewTwoDivider;
import com.shxc.smarttrade.old.myview.UPMarqueeView;
import com.shxc.smarttrade.old.presenter.AccountPresenter;
import com.shxc.smarttrade.old.presenter.PositionPresenter;
import com.shxc.smarttrade.old.utils.Arith;
import com.shxc.smarttrade.old.utils.BaseUtils;
import com.shxc.smarttrade.old.utils.BaseView;
import com.shxc.smarttrade.old.utils.CountClass;
import com.shxc.smarttrade.old.utils.MyOkHttpUtils;
import com.shxc.smarttrade.old.utils.SpUtils;
import com.shxc.smarttrade.tigerwit.activity.TigerwitOpenAccountActivity;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * Created by jcdev1 on 2017/5/9.
 */

public class PositionFragment extends Fragment implements View.OnClickListener, IViewPosition, IViewAccount {

    @BindView(R.id.btn_open_account_first)
    Button btnOpenAccountFirst;
    private View rootView;
    private int firstPosition;
    private int tagWidth;
    Animation animation = null;
    private int one;//动画偏移量
    private int tagPosition = 0;//标记当前游标位置
    LinearLayoutManager manager, xManager;

    AllPositionAdapter positionAdapter;//持仓列表适配器
    PositionPendingAdapter pendingAdapter;//挂单列表适配器
    private MyProgressDialog dialog;
    private PositionPresenter presenter = new PositionPresenter(this);
    private AccountPresenter presenterAccount = new AccountPresenter(this);

    private String symbol = "";
    private List<TraderOrder> traderOrderList;//持仓列表
    //    private ForeignOrder foreignOrder;//持仓数据
    private AccountInfo.DataBean accountInfo;//持仓界面基本数据
    private List<PendOrder.DataBean.PendOrderBean> pendOrderBeanList;//挂单列表
    private List<String> symbolList = new ArrayList<>();//用于装载两次请求中的symbol
    private Map<String, String> mapProfitCal = new HashMap<>();//保存当前symbol和收益货币转换对
    private int userId = -1;
    private boolean isHaveAccount = false;//是否开户
    private String phone;
    private int swipRefreshTag = 0;//判断当前刷新是否为SwipRefreshlayout所为
    private int isOpenAccount = -1;//开户状态：0：未开户，1：开户中，2：开户成功
    boolean isChoose = true;//判断是否同意协议
    boolean isFirstLoading = true;//判断是否是首次加载
    PositionHistoryAdapter xAdapter;

    @BindView(R.id.tv_all_position)
    TextView tvAllPosition;
    @BindView(R.id.tv_pending_order)
    TextView tvPending_order;
    @BindView(R.id.iv_tag)
    ImageView ivTag;
    @BindView(R.id.rl_view)
    RecyclerView rlView;
    @BindView(R.id.tv_center)
    TextView tvCenter;
    @BindView(R.id.tv_right)
    TextView tvRight;

    @BindView(R.id.tv_margin_free)
    TextView tvMarginFree;
    @BindView(R.id.tv_equity)
    TextView tvEquity;
    @BindView(R.id.tv_used_margin)
    TextView tvUsedMargin;
    @BindView(R.id.tv_margin_rate)
    TextView tvMarginRate;
    @BindView(R.id.tv_profit_loss)
    TextView tvProfitLoss;
    @BindView(R.id.swip_refresh)
    SwipeRefreshLayout swipRefresh;

    @BindView(R.id.ll_no_account)
    ScrollView llNoAccount;
    @BindView(R.id.ll_have_account)
    LinearLayout llHaveAccount;
    @BindView(R.id.ll_loading_error)
    LinearLayout llNetError;
    @BindView(R.id.spinner)
    Spinner spinner;
    @BindView(R.id.iv_choose)
    ImageView ivChoose;
    @BindView(R.id.tv_protocol)
    TextView tvProtocol;
    @BindView(R.id.tv_history)
    TextView tvHistory;
    @BindView(R.id.x_recycler_view)
    XRecyclerView xRecyclerView;
    @BindView(R.id.swip_refresh_account)
    SwipeRefreshLayout swipRefreshAccount;
    @BindView(R.id.ll_login_layout)
    LinearLayout llLoginLayout;
    @BindView(R.id.ll_go_login)
    LinearLayout llGoLogin;
    @BindView(R.id.btn_login)
    Button btnLogin;

    @BindView(R.id.null_view)
    LinearLayout nullView;

    @BindView(R.id.round_progress_bar)
    RoundCornerProgressBar roundProgressBar;
    @BindView(R.id.tv_account_value)
    TextView tvAccountValue;
    @BindView(R.id.tv_useful_margin)
    TextView tvUsefulMargin;
    @BindView(R.id.tv_used_margins)
    TextView tvUsedMargins;
    @BindView(R.id.tv_float_profit)
    TextView tvFloatProfit;
    //    @BindView(R.id.tv_margin_rate_new)
//    TextView tvMarginRateNew;
    @BindView(R.id.tv_profit)
    TextView tvProfit;//总盈亏
    @BindView(R.id.upview)
    UPMarqueeView upMarqueeView;
    @BindView(R.id.tv_account)
    TextView tvAccountStatus;

    private TextView textView1 = null;
    private TextView textView2 = null;
    private boolean quickClosePosition = false;//是否开启快捷平仓

    List<PositionHistory> positionHistoryListAdd = new ArrayList<>();
    private List<View> views = new ArrayList<>();

    int page = 1;
//    private AllPositionFragment allPositionFragment;

    View nullView0, nullView1, nullView2;

    MainActivity mainActivity;

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    String registerURL = (String) msg.obj;
                    Intent intent = new Intent(getActivity(), TigerwitOpenAccountActivity.class);
                    intent.putExtra("url", registerURL);
                    mainActivity.jumpType = 2;
                    startActivity(intent);
                    MobclickAgent.onEvent(getContext(), "open_account");//友盟统计该点击事件发生次数

                    break;
                case 1:
                    List<PositionHistory> positionHistoryList = (List<PositionHistory>) msg.obj;
                    if (positionHistoryList.size() != 0) {
                        positionHistoryListAdd.addAll(positionHistoryList);
                        xAdapter.setDatas(positionHistoryListAdd);
                    } else {
                        if (positionHistoryListAdd.size() == 0) {
                            //TODO 当历史记录为空
                            xRecyclerView.setVisibility(View.GONE);
                            rlView.setVisibility(View.GONE);
                            nullView.setVisibility(View.VISIBLE);
                            nullView.removeAllViews();
                            nullView.addView(nullView2);
                        } else {
                            xRecyclerView.setVisibility(View.VISIBLE);
                            rlView.setVisibility(View.VISIBLE);
                            nullView.setVisibility(View.GONE);
                            if (xRecyclerView != null)
                                xRecyclerView.setNoMore(true);
                            showMyToast("已加载全部！");
                        }
                    }
                    if (xRecyclerView != null)
                        xRecyclerView.refreshComplete();
                    break;
            }
        }
    };

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {

        if (rootView == null) {
            rootView = inflater.inflate(R.layout.fragment_position, null);
        }
        //缓存的rootView需要判断是否已经被加过parent， 如果有parent需要从parent删除，要不然会发生这个rootview已经有parent的错误。
        ViewGroup parent = (ViewGroup) rootView.getParent();
        if (parent != null) {
            parent.removeView(rootView);
        }
//        StatusBarUtil.setColor(getActivity(), Color.argb(0, 0, 0, 0));
        ButterKnife.bind(this, rootView);
        EventBus.getDefault().register(this);

        phone = SpUtils.getString(getActivity(), "telephone");

        initSpinner();
        initView();

        changeStatus();

        return rootView;
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);

        if (!hidden) {
            changeStatus();
            goAnimation(0);
        }
    }

    private void changeStatus(){

        userId = SpUtils.getInt(getActivity(), "userId", -1);
        isHaveAccount = SpUtils.getBoolean(getActivity(), "accountStatus", false);

        if (userId == -1) {
            llLoginLayout.setVisibility(View.VISIBLE);
            btnOpenAccountFirst.setText("选择经纪商开户");
        } else {
            initAdapter();
            presenter.getAccountInfo(SpUtils.getString(getContext(), "accessToken", ""), userId, -1);
            presenter.getPositionOrderList(SpUtils.getString(getContext(), "accessToken", ""), userId, -1);
            llLoginLayout.setVisibility(View.GONE);
            initListener();
        }
        if (isHaveAccount) {
            llLoginLayout.setVisibility(View.GONE);
        }
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mainActivity = (MainActivity) getActivity();
    }

    private void initSpinner() {
        List<Broker> listBroker = new ArrayList<>();
        listBroker.add(new Broker(R.mipmap.tiger_head, "TigerWit", ""));
        listBroker.add(new Broker(R.mipmap.henghua, "横华国际", ""));
        listBroker.add(new Broker(R.mipmap.yingtou, "盈透证券", ""));
        listBroker.add(new Broker(R.mipmap.kunlun, "昆仑国际", ""));
        spinner.setAdapter(new BrokerAdapter(getContext(), listBroker));
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (position > 0) {
                    spinner.setSelection(0);
                    showMyToast("敬请期待");
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        spinner.setSelection(0);
        ivChoose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isChoose) {
                    ivChoose.setImageResource(R.mipmap.agreement_no);
                    isChoose = false;
                } else {
                    ivChoose.setImageResource(R.mipmap.agreement_yes);
                    isChoose = true;

                }
            }
        });
        tvProtocol.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), UserAgreementActivity.class);
                intent.putExtra("tag", 2);
                mainActivity.jumpType = 1;
                startActivity(intent);
            }
        });

    }

    /**
     * 初始化View
     */
    private void initView() {
        //基本view处理
        tvCenter.setText(getResources().getString(R.string.position));
//        tvRight.setText(getResources().getString(R.string.history));
        swipRefresh.setColorSchemeColors(Color.RED,
                Color.argb(255, 216, 155, 60),
                Color.RED,
                Color.argb(255, 216, 155, 60));
        swipRefreshAccount.setColorSchemeColors(Color.RED,
                Color.argb(255, 216, 155, 60),
                Color.RED,
                Color.argb(255, 216, 155, 60));

        int screenWidth = getResources().getDisplayMetrics().widthPixels;
        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) ivTag.getLayoutParams();
        params.leftMargin = screenWidth / 12;
        params.width = screenWidth / 6;
        ivTag.setLayoutParams(params);
        firstPosition = 25;
        tagWidth = screenWidth / 3 - 50;
        Matrix matrix = new Matrix();
        matrix.postTranslate(0, 0);
        ivTag.setImageMatrix(matrix);// 设置动画初始位置
        one = screenWidth / 3;
        initUpView();


        nullView0 = getLayoutInflater().inflate(R.layout.nullview_position_0, null);
        nullView1 = getLayoutInflater().inflate(R.layout.nullview_position_1, null);
        nullView2 = getLayoutInflater().inflate(R.layout.nullview_position_2, null);

    }

    private void initUpView() {
        for (int i = 0; i < 2; i++) {
            LinearLayout moreView = (LinearLayout) LayoutInflater.from(getActivity()).inflate(R.layout.up_view_item_layout, null);
            if (i == 0) {
                textView1 = (TextView) moreView.findViewById(R.id.tv_explain_text1);
                TextView textView2 = (TextView) moreView.findViewById(R.id.tv_explain_text2);
                textView1.setText(" ");
                textView2.setVisibility(View.GONE);

            } else {
                LinearLayout llHaveIcon = (LinearLayout) moreView.findViewById(R.id.ll_have_icon);
                textView2 = (TextView) moreView.findViewById(R.id.tv_explain_text2);
                textView2.setText(" ");
                llHaveIcon.setVisibility(View.GONE);
            }
            views.add(moreView);
        }
        upMarqueeView.setViews(views);
    }

    int sss = 0;

    /**
     * 初始化适配器
     */
    private void initAdapter() {
        if (sss ==1) {
            return;
        }

        sss = 1;

        positionAdapter = new AllPositionAdapter(getContext());
        pendingAdapter = new PositionPendingAdapter(getContext());
        manager = new LinearLayoutManager(getContext());
        rlView.setLayoutManager(manager);
        rlView.addItemDecoration(new RecycleViewTwoDivider(getContext(), LinearLayout.VERTICAL, 20, getResources().getColor(R.color.all_background)));
        rlView.setAdapter(positionAdapter);

        manager = new LinearLayoutManager(getActivity());
        xRecyclerView.setLayoutManager(manager);
        xRecyclerView.addItemDecoration(new RecycleViewDivider(getContext(), LinearLayout.VERTICAL, 20, getResources().getColor(R.color.all_background)));
        xRecyclerView.setRefreshProgressStyle(ProgressStyle.BallSpinFadeLoader);
        xRecyclerView.setLoadingMoreProgressStyle(ProgressStyle.BallSpinFadeLoader);
        MyRefreshHeadView myRefreshHeadView = new MyRefreshHeadView(getContext());
        myRefreshHeadView.setArrowImageView(R.mipmap.indicator_arrow);
        xRecyclerView.setRefreshHeader(myRefreshHeadView);
        xRecyclerView.setFootView(new MyFootView(getContext()));
        xRecyclerView.setAdapter(xAdapter = new PositionHistoryAdapter(getContext()));
    }

    /**
     * 初始化监听器
     */
    private void initListener() {
        tvAllPosition.setOnClickListener(this);
        tvPending_order.setOnClickListener(this);
        tvHistory.setOnClickListener(this);
        swipRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                swipRefreshTag = 1;
                presenter.getAccountInfo(SpUtils.getString(getContext(), "accessToken", ""), userId, 1);
                presenter.getPositionOrderList(SpUtils.getString(getContext(), "accessToken", ""), userId, 1);
//                presenter.getForeignOrder(SpUtils.getString(getContext(), "accessToken", ""), SpUtils.getInt(getActivity(), "userId"), 1);
            }
        });

        swipRefreshAccount.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                swipRefreshTag = 1;
                presenter.getAccountInfo(SpUtils.getString(getContext(), "accessToken", ""), userId, 1);
                presenter.getPositionOrderList(SpUtils.getString(getContext(), "accessToken", ""), userId, 1);
//                presenter.getForeignOrder(SpUtils.getString(getContext(), "accessToken", ""), SpUtils.getInt(getActivity(), "userId"), 1);
            }
        });
        positionAdapter.setOnPositionItemClickListener(new PositionItemClickListener() {
            @Override
            public void onPositionItemClick(TraderOrder traderOrder, int position) {
                Intent intent = new Intent(getActivity(), StockChartUpgradeActivity.class);
                intent.putExtra("symbol", traderOrder.getSymbolEn() + "," + traderOrder.getProfitCalCurrency());
                intent.putExtra("symbolCn", traderOrder.getSymbolCn());
                intent.putExtra("tag", 1);
                intent.putExtra("digits", traderOrder.getDigits());
                Bundle bundle = new Bundle();
                bundle.putSerializable("traderOrder", traderOrder);
                intent.putExtras(bundle);
                mainActivity.jumpType = 1;
                startActivity(intent);
            }

            @Override
            public void onClosePositionClick(TraderOrder traderOrder, int position) {
                if (quickClosePosition)
                    closePosition(traderOrder.getTicket(), SpUtils.getInt(getActivity().getApplicationContext(), "userId"));
                else
                    showClosePositionDialog(traderOrder.getTicket());
            }
        });

        pendingAdapter.setOnPendingItemClickListener(new PositionPendingAdapter.PendingItemClickListener() {
            @Override
            public void itemClick(PendOrder.DataBean.PendOrderBean pendOrderBean, int position) {
                Intent intent = new Intent(getActivity(), PendingOrderDetailActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("pendOrderBean", pendOrderBean);
                intent.putExtras(bundle);
                mainActivity.jumpType = 1;
                startActivity(intent);
            }
        });

        xRecyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        positionHistoryListAdd.clear();
                        page = 1;
                        initDatas(SpUtils.getInt(getContext(), "userId"), page, 10);
                    }
                }, 1000);
            }

            @Override
            public void onLoadMore() {

                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        page++;
                        initDatas(SpUtils.getInt(getContext(), "userId"), page, 10);
                    }
                }, 1000);
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    int two = 0;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_all_position:
                goAnimation(0);
                break;
            case R.id.tv_pending_order:
                goAnimation(1);
                break;
            case R.id.tv_history:
                goAnimation(2);
                break;
        }
        animation.setFillAfter(true);// True:图片停在动画结束位置
        animation.setDuration(300);
        ivTag.startAnimation(animation);
    }

    private void goAnimation(int tag) {
        animation = new TranslateAnimation(two, one * tag, 0, 0);//四参构造函数：第一个参数表述表示动画开始的点离当前View X坐标上的差值！！！差值！！！差值！！！
        two = one * tag;                                        //八参构造函数：可相对于自身坐标也可以相对父坐标
        changeTextColor(tag);
        tagPosition = tag;
        changeAdapter(tag);
        animation.setFillAfter(true);// True:图片停在动画结束位置
        animation.setDuration(300);
        ivTag.startAnimation(animation);


        switch (tag){
            case 0:
                presenter.getAccountInfo(SpUtils.getString(getContext(), "accessToken", ""), userId, 1);
                presenter.getPositionOrderList(SpUtils.getString(getContext(), "accessToken", ""), userId, 1);
                break;
            case 1:
                presenter.getAccountInfo(SpUtils.getString(getContext(), "accessToken", ""), userId, 1);
                presenter.getPositionOrderList(SpUtils.getString(getContext(), "accessToken", ""), userId, 1);
                break;
            case 2:
                positionHistoryListAdd.clear();
                page = 1;
                initDatas(SpUtils.getInt(getContext(), "userId"), page, 10);
                break;
        }
    }

    /**
     * 改变字体颜色
     *
     * @param position
     */
    private void changeTextColor(int position) {
        if (position == 0) {
            tvAllPosition.setTextColor(getResources().getColor(R.color.main_color));
            tvPending_order.setTextColor(getResources().getColor(R.color.secondary_text_color));
            tvHistory.setTextColor(getResources().getColor(R.color.secondary_text_color));
        } else if (position == 1) {
            tvAllPosition.setTextColor(getResources().getColor(R.color.secondary_text_color));
            tvPending_order.setTextColor(getResources().getColor(R.color.main_color));
            tvHistory.setTextColor(getResources().getColor(R.color.secondary_text_color));
        } else {
            tvAllPosition.setTextColor(getResources().getColor(R.color.secondary_text_color));
            tvPending_order.setTextColor(getResources().getColor(R.color.secondary_text_color));
            tvHistory.setTextColor(getResources().getColor(R.color.main_color));
        }

    }

//    @OnClick(R.id.tv_right)
//    public void tvRight() {
//        startActivity(new Intent(getActivity(), PositionHistoryActivity.class));
//        MobclickAgent.onEvent(getContext(), "position_history");//友盟统计该点击事件发生次数
//    }


    @Override
    public void showDialog() {
        if (dialog == null) {
            dialog = new MyProgressDialog(getActivity());
            dialog.setCancelable(false);
        }
        dialog.show();
    }

    @Override
    public void dismissDialog() {
        if (dialog != null)
            dialog.dismiss();
    }

    @Override
    public void showNetErrorLayout() {
        if (llNetError != null && isFirstLoading == true) {
            llNetError.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void dismissrefresh() {
        if (swipRefresh != null)
            swipRefresh.setRefreshing(false);
        if (swipRefreshAccount != null)
            swipRefreshAccount.setRefreshing(false);
    }

    @Override
    public void showMyToast(String str) {
        try {
            MyApplication.showToast(getActivity(), str);
        } catch (Exception e) {
        }
    }

    @Override
    public void setForeignOrder(ForeignOrder foreignOrder) {
//        this.foreignOrder = foreignOrder;
//        isFirstLoading = false;
//        if (llNetError == null) return;
//        llNetError.setVisibility(View.GONE);
//        isOpenAccount = foreignOrder.getAccStatus();
//        if (foreignOrder.getAccStatus() == 2) {
//            llHaveAccount.setVisibility(View.VISIBLE);
//            llNoAccount.setVisibility(View.GONE);
//            allPositionFragment.changeFrameLayoutStatus(true);
//            SpUtils.putBoolean(getActivity(), "accountStatus", true);
//        } else if (foreignOrder.getAccStatus() == 0) {
//            if (!isHaveAccount) {
//                llHaveAccount.setVisibility(View.GONE);
//                llNoAccount.setVisibility(View.VISIBLE);
//                allPositionFragment.changeFrameLayoutStatus(false);
//                btnOpenAccountFirst.setText("立即开户");
//            }
//            return;
//        } else {
//            if (!isHaveAccount) {
//                llHaveAccount.setVisibility(View.GONE);
//                llNoAccount.setVisibility(View.VISIBLE);
//                allPositionFragment.changeFrameLayoutStatus(false);
//                btnOpenAccountFirst.setText("审核中...");
//            }
//            return;
//        }

//        traderOrderList = foreignOrder.getTraderOrder();
//
//        tvMarginFree.setText("$" + BaseUtils.getDigitsData(foreignOrder.getMarginFree(), 2));
//        tvEquity.setText("$" + BaseUtils.getDigitsData(foreignOrder.getEquity(), 2));
//        tvUsedMargin.setText("$" + BaseUtils.getDigitsData(foreignOrder.getMargin(), 2));
//        tvMarginRate.setText(foreignOrder.getMarginLevel() + "%");
//        if (foreignOrder.getTotalProfit() > 0) {
//            tvProfitLoss.setTextColor(getResources().getColor(R.color.stock_rise_color));
//        } else {
//            tvProfitLoss.setTextColor(getResources().getColor(R.color.stock_fell_color));
//        }
//        tvProfitLoss.setText(BaseUtils.dealSymbol(foreignOrder.getTotalProfit()));

//        positionAdapter.setDatas(traderOrderList, 0, null, null);
//        for (int i = 0; i < traderOrderList.size(); i++) {
//            symbolList.add(traderOrderList.get(i).getSymbolEn());
//            symbolList.add(traderOrderList.get(i).getProfitCalCurrency());
//            mapProfitCal.put(traderOrderList.get(i).getSymbolEn(), traderOrderList.get(i).getProfitCalCurrency());
//        }
//        presenter.getPendingList(SpUtils.getString(getContext(), "accessToken", ""), SpUtils.getInt(getActivity(), "userId"), swipRefreshTag);
    }

    @Override
    public void setPendingList(List<PendOrder.DataBean.PendOrderBean> pendingList) {
        this.pendOrderBeanList = pendingList;
        swipRefreshTag = 0;
        if (llNetError == null) return;
        llNetError.setVisibility(View.GONE);
        StringBuffer buffer = new StringBuffer();
        List<String> sl = new ArrayList<>();
        for (int i = 0; i < pendOrderBeanList.size(); i++) {
            symbolList.add(pendOrderBeanList.get(i).getSymbolEn());
        }
        for (int i = 0; i < symbolList.size(); i++) {
            if (sl.contains(symbolList.get(i))) continue;
            sl.add(symbolList.get(i));
            if (i == 0) {
                buffer.append(symbolList.get(i));
            } else {
                buffer.append(",");
                buffer.append(symbolList.get(i));
            }
        }
        symbol = buffer.toString();
        startListener();

    }

    /**
     * 账户基本信息
     *
     * @param accountInfo
     */
    @SuppressLint("NewApi")
    @Override
    public void setAccountInfo(AccountInfo accountInfo) {
        this.accountInfo = accountInfo.getData();
        AccountInfo.DataBean accountIn = accountInfo.getData();
        isFirstLoading = false;
        if (llNetError == null) return;
        llNetError.setVisibility(View.GONE);
        isOpenAccount = accountIn.getAccStatus();
        if (accountIn.getAccStatus() == 2) {
            llLoginLayout.setVisibility(View.GONE);
            SpUtils.putBoolean(getActivity(), "accountStatus", true);
        } else if (accountIn.getAccStatus() == 0) {
            if (!isHaveAccount) {
                llLoginLayout.setVisibility(View.VISIBLE);
                btnOpenAccountFirst.setText("选择经纪商开户");
            }
            return;
        } else {
            if (!isHaveAccount) {
                llLoginLayout.setVisibility(View.VISIBLE);
                btnOpenAccountFirst.setText("审核中...");
            }
            return;
        }

        tvUsefulMargin.setText("$" + BaseUtils.getDigitsData(accountIn.getMarginFree(), 2));
        tvAccountValue.setText("$" + BaseUtils.getDigitsData(accountIn.getEquity(), 2));
        tvUsedMargins.setText("$" + BaseUtils.getDigitsData(accountIn.getMargin(), 2));
        tvProfit.setText(BaseUtils.getDigitsData(accountIn.getCountProfitRate(), 2) + "%");
        if (accountIn.getAccType() == 0) {
            tvAccountStatus.setText("SmartTrade（模拟账户）");
            tvAccountStatus.setCompoundDrawablesWithIntrinsicBounds(
                    getActivity().getResources().getDrawable(R.drawable.st_text_icon, null),null, null, null);
        } else if (accountIn.getAccType() == 1) {
            tvAccountStatus.setText("TigerWit（" + accountIn.getMt4Id() + "）");
            tvAccountStatus.setCompoundDrawablesWithIntrinsicBounds(
                    getActivity().getResources().getDrawable(R.drawable.tiger_text_icon, null), null,null, null);
        }
//        tvMarginRateNew.setText("保证金比例：" + accountIn.getMarginLevel() + "%");
        textView1.setText("保证金比例：" + accountIn.getMarginLevel() + "%");
        setRoundProgressBarStatus(accountIn.getMarginLevel());

        if (accountIn.getTotalProfit() > 0) {
            tvFloatProfit.setTextColor(getResources().getColor(R.color.main_text_color));
        } else {
            tvFloatProfit.setTextColor(getResources().getColor(R.color.stock_fell_color));
        }
        tvFloatProfit.setText(BaseUtils.dealSymbol(accountIn.getTotalProfit()));
//        presenter.getPendingList(SpUtils.getString(getContext(), "accessToken", ""), SpUtils.getInt(getActivity(), "userId"), swipRefreshTag);

    }

    /**
     * 持仓列表
     *
     * @param positionOrderList
     */
    @Override
    public void setPositionOrderList(PositionOrderList positionOrderList) {
        if (llNetError == null) return;
        traderOrderList = positionOrderList.getData().getTraderOrder();
        positionAdapter.setDatas(traderOrderList, 0, null, null);
        for (int i = 0; i < traderOrderList.size(); i++) {
            symbolList.add(traderOrderList.get(i).getSymbolEn());
            symbolList.add(traderOrderList.get(i).getProfitCalCurrency());
            mapProfitCal.put(traderOrderList.get(i).getSymbolEn(), traderOrderList.get(i).getProfitCalCurrency());
        }
        presenter.getPendingList(SpUtils.getString(getContext(), "accessToken", ""), SpUtils.getInt(getActivity(), "userId"), swipRefreshTag);
        if (traderOrderList.size() == 0) {
            rlView.setVisibility(View.GONE);
            nullView.setVisibility(View.VISIBLE);
            nullView.removeAllViews();
            nullView.addView(nullView0);
        } else {
            rlView.setVisibility(View.VISIBLE);
            nullView.setVisibility(View.GONE);
        }
    }

    private void changeAdapter(int where) {
        //TODO 更换adapter 及其 空布局nullView
        if (where == 0) {
            xRecyclerView.setVisibility(View.GONE);
            rlView.setVisibility(View.VISIBLE);
            rlView.setAdapter(positionAdapter);
            positionAdapter.setDatas(traderOrderList, 0, null, null);

            if (traderOrderList.size() == 0) {
                rlView.setVisibility(View.GONE);
                nullView.setVisibility(View.VISIBLE);
                nullView.removeAllViews();
                nullView.addView(nullView0);
            } else {
                rlView.setVisibility(View.VISIBLE);
                nullView.setVisibility(View.GONE);
            }
        } else if (where == 1) {
            xRecyclerView.setVisibility(View.GONE);
            rlView.setVisibility(View.VISIBLE);
            rlView.setAdapter(pendingAdapter);
            pendingAdapter.setDatas(pendOrderBeanList, 0, null);

            if (pendOrderBeanList.size() == 0) {
                rlView.setVisibility(View.GONE);
                nullView.setVisibility(View.VISIBLE);
                nullView.removeAllViews();
                nullView.addView(nullView1);
            } else {
                rlView.setVisibility(View.VISIBLE);
                nullView.setVisibility(View.GONE);
            }

        } else {
            xRecyclerView.setVisibility(View.VISIBLE);
            rlView.setVisibility(View.GONE);
            if (positionHistoryListAdd.size() == 0)
                initDatas(SpUtils.getInt(getContext(), "userId"), page, 10);
            else
                xAdapter.setDatas(positionHistoryListAdd);
        }
    }

    /**
     * 启动实时消息发射器
     */
    public void startListener() {

        if (symbol.length() > 0) {
            ((MainActivity) getActivity()).startTimerListener(symbol, 2);
        }
    }

    /**
     * 必须加注解，否则无效
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(EventDatas event) {
        if (event.getTagOne().equals(EventContents.MAIN_ACTIVITY_REAL_TIME_QUOTE_FIVE)) {
            setRealTimeDatas(event);
        } else if (event.getTagOne().equals(EventContents.CLOSE_POSITION_FRAGMENT_ONE)) {
            int[] tag = (int[]) event.getResponse();
            if (tag[0] == 1 && tag[1] == 1) {
                presenter.getAccountInfo(SpUtils.getString(getContext(), "accessToken", ""), userId, 0);
                presenter.getPositionOrderList(SpUtils.getString(getContext(), "accessToken", ""), userId, 0);
//                presenter.getForeignOrder(SpUtils.getString(getContext(), "accessToken", ""), SpUtils.getInt(getActivity(), "userId"), 0);
            }
        } else if (event.getTagOne().equals(EventContents.PENDING_OEDER_DETAIL)) {
            presenter.getPendingList(SpUtils.getString(getContext(), "accessToken", ""), SpUtils.getInt(getActivity(), "userId"), swipRefreshTag);
        } else if (event.getTagOne().equals(EventContents.STOP_LOSS_OR_PROFIT_FINISH_TRADE)) {//开仓成功
            goAnimation(0);
            presenter.getAccountInfo(SpUtils.getString(getContext(), "accessToken", ""), userId, 0);
            presenter.getPositionOrderList(SpUtils.getString(getContext(), "accessToken", ""), userId, 0);
//            presenter.getForeignOrder(SpUtils.getString(getContext(), "accessToken", ""), SpUtils.getInt(getActivity(), "userId"), 0);
        } else if (event.getTagOne().equals(EventContents.PENDING_CONTROL_FINISH_PENDING)) {//挂单成功
            goAnimation(1);
            presenter.getPendingList(SpUtils.getString(getContext(), "accessToken", ""), SpUtils.getInt(getActivity(), "userId"), swipRefreshTag);
        } else if (event.getTagOne().equals(EventContents.MAIN_ACTIVITY_TELL_POSITION_REFRESH)) {
//            swipRefreshTag = 1;
//            presenter.getForeignOrder(SpUtils.getString(getContext(), "accessToken", ""), SpUtils.getInt(getActivity(), "userId"), 1);
        } else if (event.getTagOne().equals(EventContents.TRADE_ACCOUNT_ACTIVITY)) {
            swipRefreshTag = 1;
            presenter.getAccountInfo(SpUtils.getString(getContext(), "accessToken", ""), userId, 1);
            presenter.getPositionOrderList(SpUtils.getString(getContext(), "accessToken", ""), userId, 1);
        }
    }

    /**
     * 处理实时数据
     *
     * @param event
     */
    private void setRealTimeDatas(EventDatas event) {
        List<RealTimeQuoteDatas.DataBean.QuoteBean> ab = (List<RealTimeQuoteDatas.DataBean.QuoteBean>) event.getResponse();
//        Log.e("position", ab.size() + "");

        Map<String, RealTimeQuoteDatas.DataBean.QuoteBean> map = new HashMap<>();
        for (int i = 0; i < ab.size(); i++) {
            map.put(ab.get(i).getSymbol(), ab.get(i));
        }

        if (map.size() != 0) {
            setPositionRealTimeData(map);
        }
    }

    /**
     * 实时修改持仓列表数据
     *
     * @param map
     */
    private void setPositionRealTimeData(Map<String, RealTimeQuoteDatas.DataBean.QuoteBean> map) {
        List<double[]> tol = new ArrayList<>();
        double[] realTimeProfit = new double[traderOrderList.size()];
        double profitSum = 0;//浮动盈亏总和
        double allFee = 0;//过夜费加手续费总和
        for (int i = 0; i < traderOrderList.size(); i++) {
            TraderOrder tt = traderOrderList.get(i);
            String symnolEn = traderOrderList.get(i).getSymbolEn();
            if (map.containsKey(symnolEn)) {
                double realTimeData[] = {map.get(symnolEn).getMarket(), map.get(symnolEn).getAsk(), map.get(symnolEn).getBid()};
                tol.add(realTimeData);
                double[] askBidOne = new double[]{map.get(symnolEn).getAsk(), map.get(symnolEn).getBid()};
                double[] askBidThree = null;
                if (mapProfitCal.containsKey(symnolEn)) {
                    if (tt.isProfitChange())
                        askBidThree = new double[]{map.get(mapProfitCal.get(symnolEn)).getAsk(), map.get(mapProfitCal.get(symnolEn)).getBid()};
                }
                double profit2 = CountClass.getProfit(askBidOne, tt.getOpenPrice(), tt.getCmd(), askBidThree, tt.getContractSize(), tt.getVolume(), tt.isProfitChange(), tt.isProfitUSDPrex());
                realTimeProfit[i] = profit2;
                profitSum = Arith.add(profitSum, profit2);

            } else {
                realTimeProfit[i] = 0;
                double realTimeData[] = null;
                tol.add(realTimeData);
            }
            double fee = Arith.add(tt.getSwaps(), tt.getCommission());
            allFee = Arith.add(allFee, fee);
        }
        profitSum = Arith.round(Arith.add(allFee, profitSum), 2);
        if (profitSum > 0)
            tvFloatProfit.setTextColor(getResources().getColor(R.color.main_text_color));
        else
            tvFloatProfit.setTextColor(getResources().getColor(R.color.stock_fell_color));

        tvFloatProfit.setText(BaseUtils.dealSymbol(profitSum));
        double eq = Arith.round(Arith.add(accountInfo.getBalance(), profitSum), 2);
        tvAccountValue.setText("$" + BaseUtils.getDigitsData(eq, 2));
//        tvMarginRateNew.setText("保证金比例：" + Arith.mul(Arith.div(eq, accountInfo.getMargin(), 3), 100) + "%");
        textView1.setText("保证金比例：" + Arith.mul(Arith.div(eq, accountInfo.getMargin(), 3), 100) + "%");

        setRoundProgressBarStatus(Arith.mul(Arith.div(eq, accountInfo.getMargin(), 3), 100));
        tvUsefulMargin.setText("$" + BaseUtils.getDigitsData(Arith.sub(eq, accountInfo.getMargin()), 2));
        //准备挂单实时数据
        List<double[]> tol2 = new ArrayList<>();
        for (int i = 0; i < pendOrderBeanList.size(); i++) {
            PendOrder.DataBean.PendOrderBean pendOrderBean = pendOrderBeanList.get(i);
            String symbolEn = pendOrderBean.getSymbolEn();
            if (map.containsKey(symbolEn)) {
                if (pendOrderBeanList.get(i).getCmd() == 2 || pendOrderBeanList.get(i).getCmd() == 4)
                    pendOrderBeanList.get(i).setMarket(map.get(symbolEn).getBid());
                else
                    pendOrderBeanList.get(i).setMarket(map.get(symbolEn).getAsk());

                double realTimeData[] = {map.get(symbolEn).getMarket(), map.get(symbolEn).getAsk(), map.get(symbolEn).getBid()};
                tol2.add(realTimeData);
            } else {
                double realTimeData[] = null;
                tol2.add(realTimeData);
            }
        }
        if (tagPosition == 0)
            positionAdapter.setDatas(traderOrderList, 1, tol, realTimeProfit);
        else
            pendingAdapter.setDatas(pendOrderBeanList, 1, tol2);
    }

    @OnClick(R.id.btn_recharge)
    public void btnRecharge() {
        mainActivity.jumpType = 1;
        startActivity(new Intent(getActivity(), RechargeActivity.class));
        MobclickAgent.onEvent(getContext(), "position_margin_recharge");//友盟统计该点击事件发生次数
    }

    @OnClick(R.id.btn_withdraw)
    public void btnWithdraw() {
        mainActivity.jumpType = 1;
        startActivity(new Intent(getActivity(), WithdrawDepositActivity.class));
        MobclickAgent.onEvent(getContext(), "position_margin_withdraw");//友盟统计该点击事件发生次数

    }


    @Override
    public void setAccountInfomation(AccountInfomation.DataBean accountInfomation) {

    }

    @Override
    public void setUserInfo(UserInfo userInfo) {
    }

    @OnClick(R.id.btn_open_account_first)
    public void btnOpenAccountFirst() {
        if (!isChoose) {
            showMyToast("协议未通过");
        } else {

            if (userId == -1) {
                showMyToast("开户前请登录！");
                mainActivity.jumpType = 2;
                getActivity().startActivity(new Intent(getActivity(), LoginHomeActivity.class));
                MobclickAgent.onEvent(getContext(), "login");//友盟统计该点击事件发生次数

            } else {
                if (isOpenAccount == 0) {
//                    getTangerForeURL(phone, userId);
                    mainActivity.jumpType = 2;
                    startActivity(new Intent(getActivity(), ChooseBrokerActivity.class));
                } else {
                    showMyToast("审核中，请等待");
                }
            }
        }

    }

//    /**
//     * 获取老虎外汇链接
//     *
//     * @param phone
//     * @param userId
//     */
//    private void getTangerForeURL(final String phone, int userId) {
//        Map<String, String> map = new HashMap<>();
//        map.put("accessToken", SpUtils.getString(getContext(), "accessToken", ""));
//        map.put("userId", userId + "");
//        map.put("phone", phone);
//        MyOkHttpUtils.getServiceDatas(map, URLContents.ACCOUNT_FRAGMENT_REGISTERURL, new MyOkHttpUtils.ServiceStatus() {
//            @Override
//            public void faild(Call call, Exception e, int id) {
//                MyApplication.showToast(getContext(), getString(R.string.net_error));
//                dialog.dismiss();
//            }
//
//            @Override
//            public void success(String response, int id) {
//                dialog.dismiss();
//                if (response == null || new JsonParser().parse(response).isJsonNull()) {
//                    MyApplication.showToast(getContext(), getString(R.string.data_error));
//                    return;
//                }
//                JsonObject jsonObject = new JsonParser().parse(response).getAsJsonObject();
//                String errCode = "";
//                String errMsg = "";
//                if (!jsonObject.get("err_code").isJsonNull())
//                    errCode = jsonObject.get("err_code").getAsString();
//                if (!jsonObject.get("err_msg").isJsonNull())
//                    errMsg = jsonObject.get("err_msg").getAsString();
//                if (errCode.equals("0")) {
//                    JsonObject data = jsonObject.get("data").getAsJsonObject();
//                    String registerURL = "";
//                    if (!data.get("registerURL").isJsonNull())
//                        registerURL = data.get("registerURL").getAsString();
//                    Message msg = Message.obtain();
//                    msg.what = 0;
//                    msg.obj = registerURL;
//                    handler.sendMessage(msg);
//                } else {
//                    MyApplication.showToast(getContext(), errMsg);
//                }
//            }
//        });
//    }

    @OnClick(R.id.tv_margin_remind)
    public void tvMarginRemid() {
        View view = View.inflate(getActivity(), R.layout.pop_style_margin_remind, null);
        TextView tvContent = (TextView) view.findViewById(R.id.tv_content);
        TextView btnSure = (TextView) view.findViewById(R.id.btn_sure);
        String content = "\"可用保证金\"低于\"账户净值\"的20%时，将无法开仓。\"可用保证金\"≤0时，将触发系统风控进行强制平仓。如同时有多笔订单持仓，将从浮动亏损最大的订单开始平仓。请保持可用保证金大于零。";
        int strLength = content.length();
        SpannableString msp = new SpannableString(content);
        msp.setSpan(new ForegroundColorSpan(Color.RED), strLength - 12, strLength, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        tvContent.setText(msp);
        final PopupWindow popupWindow = BaseView.showPopupWindow(view, getActivity(), R.layout.fragment_position, Gravity.CENTER, BaseUtils.getScreenWidth(getContext()));
        btnSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
    }

    @OnClick(R.id.ll_margin_explain)
    public void llMarginExplain() {
        View view = View.inflate(getActivity(), R.layout.pop_style_margin_remind, null);
        TextView tvTitleHead = (TextView) view.findViewById(R.id.tv_title_head);
        tvTitleHead.setText("保证金比例");
        TextView tvContent = (TextView) view.findViewById(R.id.tv_content);
        TextView btnSure = (TextView) view.findViewById(R.id.btn_sure);
        Spanned msp;
        String htmlStr = "保证金比例=账户净值÷已用保证金<br>当保证金比例≤125%的时候，将无法开仓;</br>"
                + "<br>当保证金比例≤100%的时候，将触发系统风控进行强制平仓。如同时有多笔订单持仓，将从浮动亏损最大的订单开始平仓。</br><br><font color=\"#f61e1c\">为降低爆仓风险，建议将保证金比例维持在150%左右较为安全。"
                + "</br>";
        if (Build.VERSION.SDK_INT > 23) {
            msp = Html.fromHtml(htmlStr, Html.FROM_HTML_MODE_COMPACT);
        } else {
            msp = Html.fromHtml(htmlStr);
        }
        tvContent.setText(msp);
        final PopupWindow popupWindow = BaseView.showPopupWindow(view, getActivity(), R.layout.fragment_position, Gravity.CENTER, BaseUtils.getScreenWidth(getContext()));
        btnSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
    }

    @OnClick(R.id.ll_loading_error)
    public void llNetError() {
        presenter.getAccountInfo(SpUtils.getString(getContext(), "accessToken", ""), userId, -1);
        presenter.getPositionOrderList(SpUtils.getString(getContext(), "accessToken", ""), userId, -1);
//        presenter.getForeignOrder(SpUtils.getString(getContext(), "accessToken", ""), userId, -1);
    }

    @Override
    public void onResume() {
        super.onResume();
        quickClosePosition = SpUtils.getBoolean(getActivity(), "quickClosePosition", false);
        changeStatus();

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }


    /**
     * 弹出平仓提示框
     */
    private void showClosePositionDialog(final String ticket) {

        CommonDialog commonDialog = new CommonDialog(getActivity(), R.style.customDialogStyle);
        commonDialog.setCanceledOnTouchOutside(true);
        commonDialog.setBaseText("提示", "是否确认平仓", "取消", "确定");
        commonDialog.setYesCLickRunAble(new Runnable() {
            @Override
            public void run() {
                showDialog();
                closePosition(ticket, SpUtils.getInt(getActivity().getApplicationContext(), "userId"));
                MobclickAgent.onEvent(getContext(), "close_position");//友盟统计该点击事件发生次数
            }
        });
        commonDialog.show();
    }

    /**
     * close
     *
     * @param ticket
     * @param userId
     */
    private void closePosition(String ticket, int userId) {
        Map<String, Object> map = new HashMap<>();
        map.put("accessToken", SpUtils.getString(getContext(), "accessToken", ""));
        map.put("ticket", ticket + "");
        map.put("userId", userId + "");
        MyOkHttpUtils.getServiceDatas(getActivity(), map, URLContents.CLOSE_POSITION_FRAGMENT_CLOSE, new MyOkHttpUtils.ServiceStatus() {
            @Override
            public void faild(Call call, Exception e, int id) {
                MyApplication.showToast(getContext(), "网络异常");
                dismissDialog();
            }

            @Override
            public void success(String response, int id) {
                if (response != null) {
                    JsonObject jsonObject = new JsonParser().parse(response).getAsJsonObject();
                    String errCode = "";
                    String errMsg = "";
                    if (!jsonObject.get("err_code").isJsonNull())
                        errCode = jsonObject.get("err_code").getAsString();
                    if (!jsonObject.get("err_msg").isJsonNull())
                        errMsg = jsonObject.get("err_msg").getAsString();
                    if (errCode.equals("0")) {
//                        if (!jsonObject.get("data").isJsonNull()) {
//                            JsonObject data = jsonObject.get("data").getAsJsonObject();
//                            if (!data.get("closeTrader").isJsonNull()) {
//                                JsonObject closeTrader = data.get("closeTrader").getAsJsonObject();
//                                Gson gson = new Gson();
//                                ClosePosition cp = gson.fromJson(closeTrader, ClosePosition.class);
//
//                                Message msg = Message.obtain();
//                                msg.obj = cp;
//                                handler.sendMessage(msg);
//                            }
//                        }
                        presenter.getAccountInfo(SpUtils.getString(getContext(), "accessToken", ""), SpUtils.getInt(getActivity(), "userId"), 0);
                        presenter.getPositionOrderList(SpUtils.getString(getContext(), "accessToken", ""), SpUtils.getInt(getActivity(), "userId"), 0);
//                        presenter.getForeignOrder(SpUtils.getString(getContext(), "accessToken", ""), SpUtils.getInt(getActivity(), "userId"), 0);
                        MyApplication.showToast(getContext(), "平仓成功");
                    } else MyApplication.showToast(getContext(), errMsg);

                }
                dismissDialog();
            }
        });
    }

    /**
     * 初始化数据
     */
    private void initDatas(int userId, int page, int pagesize) {
        Map<String, Object> map = new HashMap<>();
        map.put("accessToken", SpUtils.getString(getContext(), "accessToken", ""));
        map.put("userId", userId + "");
        map.put("page", page + "");
        map.put("pagesize", pagesize + "");
        MyOkHttpUtils.getServiceDatas(getActivity(), map, URLContents.POSITION_HISTORY_ACTIVITY_HISTORYORDER, new MyOkHttpUtils.ServiceStatus() {
            @Override
            public void faild(Call call, Exception e, int id) {
                showMyToast("网络异常");
            }

            @Override
            public void success(String response, int id) {
                if (response != null) {
                    JsonObject jsonObject = new JsonParser().parse(response).getAsJsonObject();
                    String errCode = "";
                    String errMsg = "";
                    if (!jsonObject.get("err_code").isJsonNull())
                        errCode = jsonObject.get("err_code").getAsString();
                    if (!jsonObject.get("err_msg").isJsonNull())
                        errMsg = jsonObject.get("err_msg").getAsString();

                    if (errCode.equals("0")) {
                        if (!jsonObject.get("data").isJsonNull()) {
                            JsonObject data = jsonObject.get("data").getAsJsonObject();
                            if (!data.get("historyOrder").isJsonNull()) {
                                JsonArray historyOrder = data.get("historyOrder").getAsJsonArray();
                                TypeToken typeToken = new TypeToken<List<PositionHistory>>() {
                                };
                                Type type = typeToken.getType();
                                Gson gson = new Gson();
                                List<PositionHistory> positionHistoryList = gson.fromJson(historyOrder, type);
                                Message msg = Message.obtain();
                                msg.what = 1;
                                msg.obj = positionHistoryList;
                                handler.sendMessage(msg);
                            }
                        } else {
                            showMyToast("数据异常");
                        }
                    } else {
                        showMyToast(errMsg);
                    }
                }
            }
        });
    }

    @OnClick({R.id.btn_login, R.id.ll_go_login})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_login:
                mainActivity.jumpType = 1;
                getActivity().startActivity(new Intent(getActivity(), LoginHomeActivity.class));
                break;
            case R.id.ll_go_login:
                mainActivity.jumpType = 1;
                getActivity().startActivity(new Intent(getActivity(), LoginHomeActivity.class));
                break;
        }
    }

    /**
     * 设置progressBar进度及颜色
     *
     * @param marginRate
     */
    private void setRoundProgressBarStatus(double marginRate) {

        if (marginRate <= 100) {
            roundProgressBar.setProgress(0);
            textView2.setText("当前无持仓");
        } else if (marginRate > 100 && marginRate <= 150) {
            roundProgressBar.setProgressColor(getResources().getColor(R.color.denger_color));
            roundProgressBar.setProgress((float) (marginRate - 100));
            textView2.setText("极低");

        } else if (marginRate > 150 && marginRate <= 200) {
            roundProgressBar.setProgressColor(getResources().getColor(R.color.litle_color));
            roundProgressBar.setProgress((float) (marginRate - 100));
            textView2.setText("较少");
        } else if (marginRate > 200 && marginRate <= 300) {
            roundProgressBar.setProgressColor(getResources().getColor(R.color.safe_color));
            roundProgressBar.setProgress((float) (marginRate - 100));
            textView2.setText("安全");
        } else {
            roundProgressBar.setProgress(200);
            roundProgressBar.setProgressColor(getResources().getColor(R.color.safe_color));
            textView2.setText("安全");
        }
    }
}
